<style lang="less" scoped>
@import "../assets/css/config.less";
.index {
  background: #fff;
}
.loading {
  animation: myloading 1s linear infinite;
  margin-top: 100px;
}
@keyframes myloading {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.demo-list{
  font-size: 13px;
  a{
    line-height: 32px;
    padding: 5px;
  }
  span{
    padding: 5px;
  }
}
.list {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.card {
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
.submit_btn {
  width: 160px;
  margin: 20px auto;
  background-color: @color1;
  color: @white;
  font-size: 13px;
  box-shadow: none;
  border: none;
  &:hover{
    background-color: @color2;
    color: @white;
    box-shadow: none;
  }
  &:active{
    background-color: @color3;
    color: @white;
    box-shadow: none;
  }
}
.form {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
}
h4{
  margin: 15px;
  font-size:14px
}
.header{
  position: fixed;
  top:0;
  width: 100%;
  min-width: 1210px;
  z-index: 100;
}
a{
  color: @color1;
}
.button{
  margin: 15px 0 0;
  font-size: 13px;
  border-radius: 4px;
  height: 28px;
  line-height: 28px;
  padding: 0 15px;
  background-color: @color1;
  color: @white;
  border: none;
  outline: none;
  &:hover{
    background-color: @color2;
  }
  &:active{
    background-color: @color3;
  }
}
</style>
<style lang="less">
@import "../assets/css/prism.css";
</style>
<template>
  <div id="index">
    <div class="header">
      <myheader></myheader>
    </div>
    <Layout style="margin-top: 60px">
      <Layout :style="{padding: '0 24px 24px','background-color': 'white','min-width': '1210px'}">
        <div style="padding: 15px 6px">
          <my-breadcrumb :prop="breadcrumbList"></my-breadcrumb>
        </div>
        <div>
          <h4>知识点标题</h4>
          <Input v-model="title" placeholder="请输入知识点标题" style="width:300px"></Input>
        
          <h4>知识点内容</h4>
          <div ref="editor" style="text-align:left;font-size:14px"></div>
          <div v-if="params.state === 'edit'">
            <button class="button" @click="addDemo">添加练习代码</button>
            <div class="demo-list" v-for="item in demoList" :key="item._id">
              <a href="#/" @click.prevent="editCodeDemo(item._id)" :title="item.description">{{item.des}}</a>
              <span>{{item._id}}</span>
              <a href="#/" @click.prevent="editCodeDemo(item._id)">编辑</a>
            </div>
          </div>
          <div style="margin: 0 0 0 0 ">
            <h4>布鲁姆认知层次</h4>
            <Select v-model="bloom" style="width:200px">
              <Option :value="1">记忆</Option>
              <Option :value="2">理解</Option>
              <Option :value="3">应用</Option>
              <Option :value="4">分析</Option>
              <Option :value="5">综合</Option>
              <Option :value="6">评价和创造</Option>
            </Select>
          </div>
          <h4>该知识点的配题的题干</h4>
          <div ref="question_editor" style="text-align:left;font-size:14px"></div>

          <div style="margin-top : 50px">
            <h4>题型</h4>
            <Select v-model="question.type" style="width:200px">
              <Option value="panduan" key="panduan">判断</Option>
              <Option value="xuanze" key="xuanze">选择</Option>
              <Option value="jianda" key="jianda">简答</Option>
            </Select>
          </div>

          <div v-if="question.type === 'xuanze'">
            <div class="form">
              <div @click="add_item">
                <Icon type="ios-add-circle-outline"/>
                <a>增加一个选项</a>
              </div>
              <div v-for="(item, key) in question.items" :key="key">
                {{key + 1}}
                <Input
                  style="width: 500px"
                  v-model="question.items[key]"
                  size="large"
                  placeholder="请输入一个新选项"
                />
                <Icon @click="delete_Item(key)" size="15" type="md-close-circle"/>
              </div>
            </div>
          </div>

          <div>
            <h4 v-if="question.type !== 'jianda'">答案</h4>
            <Select
              v-if="question.type === 'xuanze'"
              multiple
              v-model="question.answer"
              style="width:200px"
            >
              <Option v-for="(item, key) in question.items" :key="key" :value="(key+1)+''">{{key+1}}</Option>
            </Select>
            <Select
              v-if="question.type === 'panduan'"
              v-model="question.answer"
              style="width:200px"
            >
              <Option value="yes">对</Option>
              <Option value="no">错</Option>
            </Select>
          </div>

          <h4>答案解析</h4>
          <div ref="illustration" style="text-align:left;font-size:14px"></div>
          
          <div>
            <Button
              v-if="params.state === 'new'"
              class="submit_btn"
              @click="submit()"
            >新建</Button>
            <Button
              v-if="params.state === 'edit'"
              class="submit_btn"
              @click="modify()"
            >提交修改</Button>
          </div>
        </div>
      </Layout>
    </Layout>
  </div>
</template>

<script>
import header from "../components/header.vue";
import myBreadcrumb from "../components/myBreadcrumb.vue";
import E from "wangeditor";
import { savePoint, modifyPoint, get_demos } from "../api/api";

export default {
  name: "edit_point",
  data: function() {
    return {
      editorContent: "",
      title: "",
      bloom: 0,
      question: {
        question_editor_Content: "",
        type: "",
        items: [],
        answer: "",
        illustrationContent: ""
      },
      breadcrumbList: [],
      params: {},
      demoList: []
    };
  },
  created(){
    // 获取面包屑数组
    if (JSON.parse(sessionStorage.getItem("pathList")) != null) {
      let breadcrumbList = JSON.parse(sessionStorage.getItem("pathList"));
      this.breadcrumbList = [...breadcrumbList, {name: this.params.state === 'edit'?'编辑知识点':'添加知识点'}]
    }
    if (JSON.parse(sessionStorage.getItem("editParams")) != null) {
      this.params = JSON.parse(sessionStorage.getItem("editParams"));
    }
  },
  mounted() {
    let that = this
    get_demos({
      pointId: this.params.pointId
    }).then(res => {
      if(res.state!==true) {
        this.$Message.error('获取练习代码失败')
        return
      }
      this.demoList = res.msg.map(ele => {
        return {
          UUID: ele.UUID,
          description: ele.description,
          des: ele.description.length>16 ? ele.description.slice(0, 16) + "..." : ele.description,
          point_id: ele.point_id,
          _id: ele._id
        }
      })
    }).catch(err => {
      this.$Message.error(err)
    })
    this.$nextTick(() => {
      var editor = new E(this.$refs.editor);
      var question_editor = new E(that.$refs.question_editor);
      var illustration = new E(that.$refs.illustration);

      editor.customConfig.onchange = html => {
        that.editorContent = html;
      };

      question_editor.customConfig.onchange = html => {
        that.question.question_editor_Content = html;
      };

      illustration.customConfig.onchange = html => {
        that.question.illustrationContent = html;
      };

      var url = "";
      if (process.env.NODE_ENV === "development") {
        url = "http://localhost:8080/api/uploadImg";
      } else if (process.env.NODE_ENV === "production") {
        url = "https://www.ourspark.org/api/uploadImg";
      }
      editor.customConfig.uploadImgServer = url; // 上传图片到服务器
      question_editor.customConfig.uploadImgServer = url;
      illustration.customConfig.uploadImgServer = url;

      
      editor.customConfig.zIndex = 0;
      question_editor.customConfig.zIndex = 0;
      illustration.customConfig.zIndex = 0;
      editor.create();
      question_editor.create();
      illustration.create();

      if (that.params.point === undefined) {
        editor.txt.html("<p>请在此输入知识点内容</p>");
        question_editor.txt.html("<p>请在此输入配题题干</p>");
        illustration.txt.html("<p>请在此输入配题答案解析</p>");
      } else {
        that.title = that.params.point.title;
        editor.txt.html(that.params.point.content);
        that.editorContent = that.params.point.content;

        that.bloom = that.params.point.bloom;
        question_editor.txt.html(
          that.params.point.practice.question_editor_Content
        );
        that.question.question_editor_Content = that.params.point.practice.question_editor_Content;
        that.question.type = that.params.point.practice.type;
        that.question.items = that.params.point.practice.items;
        that.question.answer = that.params.point.practice.answer;
        illustration.txt.html(
          that.params.point.practice.illustrationContent
        );
        that.question.illustrationContent = that.params.point.practice.illustrationContent;
      }
    })

  },
  components: {
    myheader: header,
    'my-breadcrumb': myBreadcrumb
  },
  methods: {
    editCodeDemo(id){
      sessionStorage.setItem(
        "runnob",
        JSON.stringify({
          from: "editPoint",
          pointId: this.params.pointId,
          demoId: id
        })
      );
      this.$router.push({
        name: 'runnob'
      })
    },
    addDemo(){
      sessionStorage.setItem(
        "runnob",
        JSON.stringify({
          from: "editPoint",
          pointId: this.params.pointId
        })
      );
      this.$router.push({
        name: 'runnob'
      })
    },
    add_item() {
      this.question.items.push("");
    },
    delete_Item(key) {
      this.question.items.splice(key, 1);
    },
    modify() {
      if (this.title === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "知识点标题不能为空哦！"
        });
      } else if (this.editorContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "知识点内容不能为空哦！"
        });
      } else if (this.question.question_editor_Content === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题干不能为空哦！"
        });
      } else if (this.bloom === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "布鲁姆认知层次必须选！"
        });
      } else if (this.question.type === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题型必须选！"
        });
      } else if (
        this.question.type === "xuanze" &&
        this.question.items.length == 0
      ) {
        this.$Modal.confirm({
          title: "提示",
          content: "不能没有选项！"
        });
      } else if (this.question.type!=="jianda" && this.question.answer === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案！"
        });
      } else if (this.question.type!=="jianda" && this.question.illustrationContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案解析！"
        });
      } else {
        let re = /<a href="demo:\/\/([^"]+)"[^>]+>/g
        let text = this.editorContent
        let i 
        while (i= re.exec(this.editorContent)) {
          text = text.replace(i[0] , `<a href="/#/runnob?id=${i[1]}" class="code-demo">`)
        }
        
        let reTable = /<table[^>]*>/g
        text = text.replace(reTable, (res)=>{
          return `<table class="point-table">`
        })
        modifyPoint({
          menu: this.params.position,
          pointId: this.params.pointId,
          content: text,
          title: this.title,
          practice: this.question,
          bloom: this.bloom
        })
          .then(response => {
            if (response.state === true) {
              this.$Message.success("修改成功");
              this.$router.go(-1);
            } else {
              this.$Message.error("修改失败！ " + response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      }
    },
    submit() {
      if (this.title === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "知识点标题不能为空哦！"
        });
      } else if (this.editorContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "知识点内容不能为空哦！"
        });
      } else if (this.question.question_editor_Content === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题干不能为空哦！"
        });
      } else if (this.bloom === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "布鲁姆认知层次必须选！"
        });
      } else if (this.question.type === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "题型必须选！"
        });
      } else if (
        this.question.type === "xuanze" &&
        this.question.items.length == 0
      ) {
        this.$Modal.confirm({
          title: "提示",
          content: "不能没有选项！"
        });
      } else if (this.question.type !== 'jianda' && this.question.answer === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案！"
        });
      } else if (this.question.type !== 'jianda' && this.question.illustrationContent === "") {
        this.$Modal.confirm({
          title: "提示",
          content: "必须提供该题答案解析！"
        });
      } else {
        savePoint({
          menu: this.params.position,
          seq: parseInt(this.params.seq) + 1,
          content: this.editorContent,
          title: this.title,
          practice: this.question,
          bloom: this.bloom
        })
          .then(response => {
            if (response.state === true) {
              this.$Message.success("提交成功");
              this.$router.go(-1);
            } else {
              this.$Message.error("提交失败！ " + response.msg);
            }
          })
          .catch(error => {
            this.$Message.error(error.status);
          });
      }
    }
  }
};
</script>